package com.suse.lhw.hms.authserver.POJO;

import com.suse.lhw.hms.authserver.constan.UserConstant;
import com.suse.lhw.hms.authserver.domin.UPermission;
import com.suse.lhw.hms.authserver.service.UPermissionService;
import lombok.Data;
import netscape.security.Privilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.authserver.domin
 * @ClassName: AuthUserDetail
 * @Description: java类作用描述
 * @Author: 李鸿炜
 * @CreateDate: 2020/4/9 11:30
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/4/9 11:30
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Data
public class AuthUserDetail extends AuthUserPoJo implements UserDetails {
    private static final long serialVersionUID = 1L;

    public AuthUserDetail(AuthUserPoJo user) {
        if (user != null) {
            this.setUserName(user.getUserName());
            this.setPassWord(user.getPassWord());
            this.setStatus(user.getStatus());
            this.setRoleInfos(user.getRoleInfos());
            this.setPermissionInfos(user.getPermissionInfos());
        }
    }

    @Autowired
    UPermissionService uPermissionService;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
        List<UPermission> permissions = uPermissionService.getUsersPermissions(this.getUsername());
        if (permissions != null) {
            for (UPermission p : permissions) {
                GrantedAuthority grantedAuthority = new MyGrantedAuthority(p.getUrl(), p.getMethod());
                authorityList.add(grantedAuthority);
            }
        }
        return authorityList;
    }

    @Override
    public String getPassword() {
        return super.getPassWord();
    }

    @Override
    public String getUsername() {
        return super.getUserName();
    }


    /**
     * 账户是否过期
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {

        return true;
    }

    /**
     * 是否禁用
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {

        return true;
    }

    /**
     * 密码是否过期
     *
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {

        return true;
    }

    /**
     * 是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return UserConstant.USER_STATUS_NORMAL.equals(this.getStatus()) ? true : false;
    }
}
